import authority from '@/utils/authority'
import dynamicRoutes from '@/router/dynamicRoutes'

const constantsPaths = ['/', '/home', '*']

function permissionMenu(routerMap, authMenuMap) {
  return routerMap.filter(item => {
    const hasPermission = authMenuMap[item.path] || constantsPaths.includes(item.path)
    if (hasPermission && item.children && item.children.length) {
      item.children = permissionMenu(item.children, authMenuMap)
    }
    return hasPermission
  })
}

function copyMenu(routes = []) {
  return routes.map(item => {
    const newItem = {
      path: item.path,
      name: item.name,
      meta: item.meta || {},
    }
    if (item.hidden) newItem.hidden = true
    if (item.hideChildrenInMenu) newItem.hideChildrenInMenu = true
    if (item.children && item.children.length) {
      newItem.children = copyMenu(item.children)
    }
    return newItem
  })
}

function getRouter() {
  const user = authority.get() || {}
  const { menu = [], is_admin } = user
  if (is_admin) return dynamicRoutes
  const authMenuMap = menu.reduce(((res, path) => {
    res[path] = 1
    return res
  }), {})
  return permissionMenu(dynamicRoutes, authMenuMap)
}

const state = {
  generated: false,
  menus: [],
  addRouters: []
}

const mutations = {
  SET_MENUS(state, payload) {
    Object.assign(state, payload)
  }
}

const actions = {
  generateRoutes({ state, commit }) {
    if (state.generated) return []
    return new Promise(resolve => {
      const newRoutes = getRouter()
      const { children } = newRoutes[0] || {}
      commit("SET_MENUS", {
        menus: copyMenu(children),
        generated: true,
      })
      resolve(newRoutes)
    })
  },
}

export default {
  state,
  mutations,
  actions
}